import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/HomeView.vue'
import store from '@/store';
import { computed } from 'vue';
import { useStore } from 'vuex';



const routes = [
  {
    path: '/',
    name: 'home',
    component: LoginView,
    meta: {
      require: true //这个页面要权限
    }
  },
  {
    path: '/reg',
    name: 'reg',
    component: () => import('../views/RegView.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue'),
    beforeEnter: (to, from, next) => {
      const store = useStore();
      const isLogin = computed(() => store.state.isLogin);
      if (isLogin.value) {
        next('/'); // 如果已登录，重定向到主页
      } else {
        next();
      }
    }
  },


]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const store = useStore();
  const isLogin = computed(() => store.state.isLogin);
  console.log("vuex的isLogin值:===>",isLogin.value);
  
  if (isLogin.value || to.path === '/login') {
    next();
  } else {
    next('/login');
  }
});

export default router
